package cn.lili.listener;

import cn.lili.common.security.enums.SceneEnums;
import cn.lili.modules.member.client.UserClient;
import cn.lili.modules.member.entity.dos.User;
import cn.lili.modules.member.entity.dto.UserSearchParams;
import cn.lili.modules.message.client.NoticeMessageClient;
import cn.lili.modules.message.entity.dos.MemberMessage;
import cn.lili.modules.message.entity.dos.Message;
import cn.lili.modules.message.entity.dto.NoticeMessageDTO;
import cn.lili.modules.message.entity.enums.MessageSendClient;
import cn.lili.modules.message.entity.enums.MessageStatusEnum;
import cn.lili.modules.message.entity.enums.RangeEnum;
import cn.lili.modules.sms.entity.dto.SmsReachDTO;
import cn.lili.modules.store.client.StoreClient;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.store.entity.dto.StoreSearchParams;
import cn.lili.modules.system.client.MemberMessageClient;
import cn.lili.modules.system.client.SmsClient;
import cn.lili.modules.system.entity.params.SmsParams;
import cn.lili.routing.MsgRoutingKey;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 站内信通知
 *
 * @author paulG
 * @since 2020/12/9
 */
@Component
@RequiredArgsConstructor
public class NoticeMessageListener {

    /**
     * 站内信
     */
    private final NoticeMessageClient noticeMessageClient;

    /**
     * 会员
     */
    private final UserClient userClient;

    /**
     * 短信
     */
    private final SmsClient smsClient;


    /**
     * 会员消息
     */
    private final MemberMessageClient memberMessageClient;

    /**
     * 店铺
     */
    private final StoreClient storeClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "${lili.amqp.msg}" + "_" + MsgRoutingKey.NOTICE),
            exchange = @Exchange(value = "${lili.amqp.msg}"),
            key = MsgRoutingKey.NOTICE))
    public void notice(NoticeMessageDTO noticeMessageDTO) {
        noticeMessageClient.noticeMessage(noticeMessageDTO);
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "${lili.amqp.msg}" + "_" + MsgRoutingKey.SMS),
            exchange = @Exchange(value = "${lili.amqp.msg}"),
            key = MsgRoutingKey.SMS))
    public void smsReach(SmsReachDTO smsReachDTO) {

        //发送全部会员
        if (smsReachDTO.getSmsRange().equals(RangeEnum.ALL.name())) {
            //获取所有会员的手机号
            List<String> list = userClient.getAllMemberMobile();

            SmsParams smsParams =
                    SmsParams.builder().signName(smsReachDTO.getSignName()).mobiles(list).templateCode(smsReachDTO.getMessageCode()).build();

            smsClient.sendBatchSms(smsParams);
            //判断为发送部分用户
        } else {

            SmsParams smsParams =
                    SmsParams.builder().signName(smsReachDTO.getSignName()).mobiles(smsReachDTO.getMobile()).templateCode(smsReachDTO.getMessageCode()).build();

            smsClient.sendBatchSms(smsParams);
        }
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "${lili.amqp.msg}" + "_" + MsgRoutingKey.MESSAGE),
            exchange = @Exchange(value = "${lili.amqp.msg}"),
            key = MsgRoutingKey.MESSAGE))
    public void message(Message message) {
        // 管理端发送给商家的站内信
        if (message.getMessageClient().equals(MessageSendClient.STORE.name().toLowerCase())) {
            saveStoreMessage(message);
        } else {
            //管理员发送给会员的站内信
            saveMemberMessage(message);
        }
    }


    /**
     * 保存店铺消息
     *
     * @param message 消息
     */
    private void saveStoreMessage(Message message) {
        List<MemberMessage> list = new ArrayList<>();
        //发送全部商家情况
        if ("ALL".equals(message.getMessageRange())) {
            StoreSearchParams storeSearchParams = new StoreSearchParams();
            storeSearchParams.setStoreStatus("OPEN");
            List<Store> storeList = storeClient.list(storeSearchParams);
            storeList.forEach(item -> {
                MemberMessage memberMessage = new MemberMessage();
                memberMessage.setMessageId(message.getId());
                memberMessage.setMemberName(item.getStoreName());
                memberMessage.setMemberId(item.getId());
                memberMessage.setStatus(MessageStatusEnum.UN_READY.name());
                memberMessage.setTitle(message.getTitle());
                memberMessage.setContent(message.getContent());
                list.add(memberMessage);
            });
        } else {
            //发送给指定商家情况
            int i = 0;
            for (String str : message.getUserIds()) {
                MemberMessage memberMessage = new MemberMessage();
                memberMessage.setMessageId(message.getId());
                memberMessage.setMemberId(str);
                memberMessage.setMemberName(message.getUserNames()[i]);
                memberMessage.setStatus(MessageStatusEnum.UN_READY.name());
                memberMessage.setTitle(message.getTitle());
                memberMessage.setContent(message.getContent());
                list.add(memberMessage);
                i++;
            }
        }
        if (!list.isEmpty()) {
            //执行保存
            memberMessageClient.save(list);
        }
    }

    /**
     * 保存会员消息
     *
     * @param message 消息
     */
    private void saveMemberMessage(Message message) {
        List<MemberMessage> list = new ArrayList<>();
        //如果是给所有会员发送消息
        if ("ALL".equals(message.getMessageRange())) {
            //构建分页查询参数
            //100条查一次
            int pageSize = 100;
            for (int i = 1; ; i++) {
                UserSearchParams searchParams = new UserSearchParams();
                searchParams.setScene(SceneEnums.MEMBER);
                searchParams.setEnable(true);
                searchParams.setPageSize(pageSize);
                searchParams.setPageNumber(i);
                List<User> memberList = userClient.list(searchParams);
                if (memberList.isEmpty()) {
                    break;
                }
                //循环要保存的信息
                memberList.forEach(item -> {
                    MemberMessage memberMessage = new MemberMessage();
                    memberMessage.setContent(message.getContent());
                    memberMessage.setTitle(message.getTitle());
                    memberMessage.setMessageId(message.getId());
                    memberMessage.setMemberId(item.getId());
                    memberMessage.setMemberName(item.getUsername());
                    memberMessage.setStatus(MessageStatusEnum.UN_READY.name());
                    list.add(memberMessage);
                });
            }

        } else {
            //如果是给指定会员发送消息
            int i = 0;
            for (String str : message.getUserIds()) {
                MemberMessage memberMessage = new MemberMessage();
                memberMessage.setMessageId(message.getId());
                memberMessage.setMemberId(str);
                memberMessage.setMemberName(message.getUserNames()[i]);
                memberMessage.setStatus(MessageStatusEnum.UN_READY.name());
                memberMessage.setTitle(message.getTitle());
                memberMessage.setContent(message.getContent());
                list.add(memberMessage);
                i++;
            }
        }
        if (!list.isEmpty()) {
            //执行保存
            memberMessageClient.save(list);
        }

    }


}
